// pages/exam/exam.js
const app = getApp();
Page({
  data: {
    screenHeight: app.globalData.safearea.height,
    windowHeight: app.globalData.safearea.windowHeight,
    isNull: false,
    current: 0,

    viewMode: app.globalData.exam1ViewMode,
    showAnswer: app.globalData.exam1ShowAnswer,
    progressWidth: 0,
  },
  onShow() {
    if (!app.globalData.token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(()=> {
        wx.switchTab({
          url: '/pages/index/index',
        });
      }, 1500);
      return;
    }
    // 加载app.globalData.exam1Params
    if (!('vip' in app.globalData.userinfo) || JSON.stringify(app.globalData.userinfo.vip) === '{}') {
      console.log('当前', app.globalData.userinfo)
      wx.showModal({
        title: '开通会员',
        content: '解锁本专业全部题目',
        confirmText: '确认开通',
        cancelText: '返回首页',
        complete: (res) => {
          if (res.cancel) {
            wx.switchTab({
              url: '/pages/index/index'
            });
          }
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/buy/buy'
            });
          }
        }
      })
    }
    // if (app.globalData.exam1ParamsNeedLoad) {
      this.setData({
        examList: [],
        current: 0,
        viewMode: app.globalData.exam1ViewMode,
        title: app.globalData.exam1Title,
        showAnswer: app.globalData.exam1ShowAnswer,
        isNull: false,
        progressWidth: 0
      });
      const that = this;
      wx.showLoading({
        title: '加载题目'
      });
      that.loadData();
      if (app.globalData.exam1Title === '模拟成绩') {
        // 开启一个计时器
        this.time = 0;
        this.timeIntval = setInterval(() => {
          this.time++;
        }, 1000);
      }
    // }
  },
  loadData() {
    let category = app.globalData.category;
    const that = this;
    app.globalData.exam1Params.category_id = category.id;
    if (app.globalData.exam1Params.type_id instanceof Array) {
      app.globalData.exam1Params.type_id = app.globalData.exam1Params.type_id.join(',');
    }
    app.request('/api/question/list', app.globalData.exam1Params).then(res => {
      app.globalData.exam1ParamsNeedLoad = false;
      const data = res.data.data;
      for(let i = 0;i < res.data.data.length;i++) {
        let options = JSON.parse(data[i].option_json);
        let options_arr = [];
        for(let option in options) {
          options_arr.push({name: option, value: options[option]});
        }
        
        if (app.globalData.exam1ViewMode) {
          data[i].show_answer = true;
          data[i].selected = data[i].answer_tags.split(',');
        } else {
          data[i].show_answer = false;
          data[i].selected = [];
        }
        data[i].option_json = options_arr;
      }
      if (data.length > 0) {
        that.setData({
          progressWidth: 1 / data.length * 100,
          examList: data
        });
      } else {
        that.setData({
          isNull: true
        });
      }
      console.log(data);
      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
      console.error(err);
    })
  },
  selectOption(e) {
    const examList = this.data.examList;
    const item = examList[e.target.dataset.itemindex];
    const option = item.option_json[e.target.dataset.optionindex];
    let selected = item.selected;
    if (item.show_answer) return;
    if (item.question_type_id == 2) {
      // 多选
      let sindex = selected.indexOf(option.name)
      if (sindex > -1) {
        selected.splice(sindex, 1)
      } else {
        selected.push(option.name)
      }
      selected = selected.sort();
    } else {
      // 判断题与单选题
      selected = [option.name];
      this.saveExam(item.id, selected.join(','));
      this.setData({
        [`examList[${e.target.dataset.itemindex}].show_answer`]: true
      });
    }
    this.setData({
      [`examList[${e.target.dataset.itemindex}].selected`]: selected,
    });
  },
  
  onSwiperChange (e) {
    if (e.detail.source === 'touch') {
      this.setData({
        current: e.detail.current,
        progressWidth: ((e.detail.current + 1) / this.data.examList.length) * 100 // 计算进度条宽度百分比
      });
    }
  },
  doCollect() {
    const item = this.data.examList[this.data.current];
    const that = this;
    let star = item.star ? 0 : 1;
    that.setData({
      [`examList[${that.data.current}].star`]: star
    });
    app.request('/api/question/userStar', {question_id: item.id, star: star}, 'POST').then(res => {
    }).catch(err => {
      console.error(err);
    });
  },
  showAnswer: function (e) {
    const examList = this.data.examList;
    if (examList[e.target.dataset.index].selected.length <= 0) return;
    this.setData({
      [`examList[${e.target.dataset.index}].show_answer`]: true
    });
    // 保存答题记录
    this.saveExam(examList[e.target.dataset.index].id, examList[e.target.dataset.index].selected.join(','));
  },
  saveExam(id, answer) {
    if (app.globalData.exam1Title === '随机练习' || app.globalData.exam1Title === '单选题' || app.globalData.exam1Title === '多选题' || app.globalData.exam1Title === '判断题') {
      app.request('/api/question/userAnswer', {question_id: id, answer: answer}, 'POST').then(res => {
      }).catch(err => {
        console.error(err);
      })
    }
  },
  prevQuestion: function () {
    if (this.data.current === 0) return;
    let i = this.data.current - 1;
    console.log('i', i);
    this.setData({
      current: i,
      progressWidth: ((i+1) / this.data.examList.length) * 100
    });
  },
  nextQuestion: function () {
    if ((this.data.current+1) >= this.data.examList.length) return;
    let i = this.data.current + 1;
    console.log('i', i);
    this.setData({
      current: i,
      progressWidth: ((i+1) / this.data.examList.length) * 100
    });
  },
  goBack() {
    wx.navigateBack();
  }
});
